<template>
  <n-form
    ref="formRef"
    :model="formData"
    :rules="rules"
    label-placement="left"
    label-width="auto"
    require-mark-placement="right-hanging"
    :disabled="isSubmitting"
    class="py-4"
  >
    <n-grid :cols="2" :x-gap="24">
      <n-form-item-grid-item label="授课干部" path="cadreId">
        <n-select
          v-model:value="formData.cadreId"
          placeholder="请选择授课干部"
          :options="cadreOptions"
          :loading="cadreStore.loading"
          :disabled="fixedCadre"
          filterable
          clearable
          @update:value="handleCadreChange"
        />
      </n-form-item-grid-item>

      <n-form-item-grid-item label="授课高校" path="universityId">
        <n-select
          v-model:value="formData.universityId"
          :placeholder="formData.cadreId ? '请选择授课高校（优先显示干部意向高校）' : '请先选择授课干部'"
          :options="universityOptions"
          :loading="universityStore.loading"
          :disabled="!formData.cadreId"
          filterable
          clearable
        />
      </n-form-item-grid-item>

      <n-form-item-grid-item label="课程系列" path="courseSeries">
        <n-select
          v-model:value="formData.courseSeries"
          placeholder="请选择课程系列"
          :options="courseSeriesOptions"
          clearable
        />
      </n-form-item-grid-item>

      <n-form-item-grid-item label="课程名称" path="courseName">
        <n-input v-model:value="formData.courseName" placeholder="请输入课程名称" />
      </n-form-item-grid-item>

      <n-form-item-grid-item label="上课日期" path="classDate">
        <n-date-picker v-model:value="formData.classDate" type="date" placeholder="请选择上课日期" style="width: 100%;" />
      </n-form-item-grid-item>

      <n-form-item-grid-item label="上课时间" path="classTime">
        <n-input v-model:value="formData.classTime" placeholder="请输入上课时间 (如: 09:00-11:00)" />
      </n-form-item-grid-item>

      <n-form-item-grid-item label="授课地点" path="location">
        <n-input v-model:value="formData.location" placeholder="请输入授课地点" />
      </n-form-item-grid-item>

      <n-form-item-grid-item label="计划学时" path="plannedHours">
        <n-input-number v-model:value="formData.plannedHours" placeholder="请输入计划学时" :min="0.5" :step="0.5" style="width: 100%;">
          <template #suffix>学时</template>
        </n-input-number>
      </n-form-item-grid-item>
      
      <n-form-item-grid-item label="授课学期" path="teachingSemester">
        <n-select
          v-model:value="formData.teachingSemester"
          placeholder="请选择授课学期"
          :options="semesterOptions" 
          clearable
        />
      </n-form-item-grid-item>

      <n-form-item-grid-item label="授课状态" path="teachingStatus">
        <n-select
          v-model:value="formData.teachingStatus"
          placeholder="请选择授课状态"
          :options="teachingStatusOptions"
          clearable
        />
      </n-form-item-grid-item>

      <n-form-item-grid-item :span="2" label="备注" path="remarks">
        <n-input
          v-model:value="formData.remarks"
          type="textarea"
          placeholder="请输入备注信息"
          :autosize="{ minRows: 3, maxRows: 5 }"
        />
      </n-form-item-grid-item>
    </n-grid>

    <div class="flex justify-between mt-6">
      <div>
        <n-button @click="generateMockData" type="info" ghost>
          🎲 一键生成虚拟信息
        </n-button>
      </div>
      <div>
        <n-button @click="handleCancel" :disabled="isSubmitting" class="mr-4">取消</n-button>
        <n-button type="primary" @click="handleSubmit" :loading="isSubmitting" :disabled="isSubmitting">
          {{ initialData ? '保存更新' : '创建' }}
        </n-button>
      </div>
    </div>
  </n-form>
</template>

<script setup>
import { ref, watch, defineProps, defineEmits, onMounted, computed } from 'vue';
import {
  NForm,
  NFormItemGridItem,
  NInput,
  NSelect,
  NDatePicker,
  NInputNumber,
  NButton,
  NGrid,
  useMessage
} from 'naive-ui';
import { useCadreStore } from '@/stores/cadreStore';
import { useUniversityStore } from '@/stores/universityStore';
import { teachingStatusOptions, semesterOptions, courseSeriesOptions } from '@/utils/planOptions';

const props = defineProps({
  initialData: {
    type: Object,
    default: null,
  },
  fixedCadre: {
    type: Boolean,
    default: false,
  },
});

const emits = defineEmits(['submit', 'cancel']);

const message = useMessage();
const formRef = ref(null);
const cadreStore = useCadreStore();
const universityStore = useUniversityStore();

const defaultFormValues = {
  _id: null,
  cadreId: null,
  universityId: null,
  courseSeries: null,
  courseName: '',
  classDate: null,
  classTime: '',
  location: '',
  plannedHours: null,
  teachingStatus: '计划中',
  teachingSemester: null,
  remarks: '',
};

const formData = ref({ ...defaultFormValues });
const isSubmitting = ref(false);

const cadreOptions = computed(() =>
  cadreStore.allCadres.map(c => ({ label: c.name, value: c._id }))
);

// 获取当前选中干部的信息
const selectedCadre = computed(() => {
  if (!formData.value.cadreId) return null;
  return cadreStore.allCadres.find(c => c._id === formData.value.cadreId);
});

// 构建分组的高校选项
const universityOptions = computed(() => {
  const allUniversities = universityStore.allUniversities;
  const selectedCadreData = selectedCadre.value;

  if (!selectedCadreData) {
    // 如果没有选中干部，返回普通的高校列表
    return allUniversities.map(u => ({ label: u.schoolName, value: u._id }));
  }

  // 获取干部的意向高校ID列表，处理可能的嵌套对象
  const getUniversityId = (universityData) => {
    if (!universityData) return null;
    if (typeof universityData === 'object') {
      return universityData._id || universityData.id;
    }
    return universityData;
  };

  const intendedUniversityIds = [
    getUniversityId(selectedCadreData.intendedUniversity1),
    getUniversityId(selectedCadreData.intendedUniversity2),
    getUniversityId(selectedCadreData.intendedUniversity3)
  ].filter(id => id); // 过滤掉null/undefined

  // 分离意向高校和其他高校
  const intendedUniversities = [];
  const otherUniversities = [];

  allUniversities.forEach(university => {
    const universityId = university._id;
    const option = { label: university.schoolName, value: universityId };

    if (intendedUniversityIds.includes(universityId)) {
      intendedUniversities.push(option);
    } else {
      otherUniversities.push(option);
    }
  });

  // 如果有意向高校，返回分组选项
  if (intendedUniversities.length > 0) {
    return [
      {
        type: 'group',
        label: '干部意向高校',
        key: 'intended',
        children: intendedUniversities
      },
      {
        type: 'group',
        label: '其他高校',
        key: 'others',
        children: otherUniversities
      }
    ];
  }

  // 如果没有意向高校，返回普通列表
  return otherUniversities;
});

const rules = {
  cadreId: { required: true, message: '请选择授课干部', trigger: 'change' },
  universityId: { required: true, message: '请选择授课高校', trigger: 'change' },
  courseName: { required: true, message: '请输入课程名称', trigger: ['input', 'blur'] },
  classDate: { type: 'number', required: true, message: '请选择上课日期', trigger: 'change' },
  classTime: { required: true, message: '请输入上课时间', trigger: ['input', 'blur'] },
  location: { required: true, message: '请输入授课地点', trigger: ['input', 'blur'] },
  plannedHours: { 
    type: 'number', required: true, message: '请输入计划学时', trigger: ['blur', 'change'],
    validator: (rule, value) => (value != null && value > 0) || new Error('学时必须是大于0的数字')
  },
  teachingStatus: { required: true, message: '请选择授课状态', trigger: 'change' },
  teachingSemester: { required: true, message: '请选择授课学期', trigger: 'change' }
};

watch(() => props.initialData, (newData) => {
  if (newData) {
    formData.value = {
      ...defaultFormValues,
      ...newData,
      classDate: newData.classDate ? new Date(newData.classDate).getTime() : null,
    };
  } else {
    formData.value = { ...defaultFormValues };
  }
}, { immediate: true, deep: true });

const handleCadreChange = () => {
  // 当干部改变时，清空已选择的高校，让用户重新选择
  formData.value.universityId = null;

  // universityOptions 是 computed，会自动重新计算
  console.log('干部已更改，高校选项已更新');
};

const handleSubmit = async (e) => {
  if (isSubmitting.value) return; // 防止重复提交

  e.preventDefault();
  try {
    isSubmitting.value = true;
    await new Promise((resolve, reject) => {
      formRef.value?.validate((errors) => {
        if (!errors) {
          resolve();
        } else {
          reject(new Error('表单验证失败'));
        }
      });
    });
      // 验证必填字段
      if (!formData.value.cadreId) {
        message.error('请选择授课干部');
        return;
      }
      if (!formData.value.universityId) {
        message.error('请选择授课高校');
        return;
      }

      // 确保数据格式正确
      const submitData = {
        ...formData.value,
        classDate: formData.value.classDate ? new Date(formData.value.classDate) : null,
        // 确保ID字段是字符串格式且有效
        cadreId: String(formData.value.cadreId).trim(),
        universityId: String(formData.value.universityId).trim(),
        // 确保数字字段是正确的类型
        plannedHours: Number(formData.value.plannedHours),
        // 确保字符串字段被正确处理
        courseName: String(formData.value.courseName || '').trim(),
        classTime: String(formData.value.classTime || '').trim(),
        location: String(formData.value.location || '').trim(),
        teachingStatus: String(formData.value.teachingStatus || '计划中'),
        teachingSemester: String(formData.value.teachingSemester || '').trim(),
        remarks: String(formData.value.remarks || '').trim(),
      };

      // 移除空的_id字段（新建时不需要）
      if (!submitData._id) {
        delete submitData._id;
      }

      // 移除空的courseSeries字段
      if (!submitData.courseSeries) {
        delete submitData.courseSeries;
      }

    console.log('准备提交的数据:', submitData);
    await emits('submit', submitData);
  } catch (error) {
    console.error('表单提交失败:', error);
    message.error('请检查表单填写是否正确');
  } finally {
    isSubmitting.value = false;
  }
};

const handleCancel = () => {
  emits('cancel');
};

const resetForm = () => {
  formData.value = { ...defaultFormValues };
  formRef.value?.restoreValidation();
};

// 生成虚拟数据的函数
const generateMockData = () => {
  const courseNames = [
    '新时代领导力提升专题', '公共政策制定与执行', '经济发展新动能培育',
    '社会治理创新实践', '文化自信与传承发展', '生态文明建设路径',
    '国家安全战略解读', '外交政策与国际关系', '党风廉政建设专题',
    '数字化转型与治理', '乡村振兴战略实施', '区域协调发展战略'
  ];

  const locations = [
    '主楼201教室', '图书馆报告厅', '行政楼会议室', '学术交流中心',
    '综合楼阶梯教室', '国际会议厅', '多媒体教室A座', '培训中心大厅'
  ];

  const times = [
    '09:00-11:00', '14:00-16:00', '19:00-21:00', '10:00-12:00', '15:00-17:00'
  ];

  // 保存当前的干部ID（如果是排课模式）
  const currentCadreId = props.fixedCadre ? formData.value.cadreId : null;

  if (cadreOptions.value.length > 0) {
    const randomCourseSeries = courseSeriesOptions[Math.floor(Math.random() * courseSeriesOptions.length)];

    // 如果不是固定干部模式，随机选择干部
    if (!props.fixedCadre) {
      const randomCadre = cadreOptions.value[Math.floor(Math.random() * cadreOptions.value.length)];
      formData.value.cadreId = randomCadre.value;
    } else {
      // 如果是固定干部模式（排课），保持当前干部不变
      console.log('排课模式：保持干部不变，只生成其他虚拟数据');
    }

    // 等待下一个tick，确保高校选项已更新（特别是在干部改变时）
    setTimeout(() => {
      let randomUniversity = null;

      // 获取当前的高校选项
      const currentUniversityOptions = universityOptions.value;

      if (Array.isArray(currentUniversityOptions) && currentUniversityOptions.length > 0) {
        // 检查是否有分组选项
        const hasGroups = currentUniversityOptions.some(option => option.type === 'group');

        if (hasGroups) {
          // 如果有分组，优先从意向高校中选择
          const intendedGroup = currentUniversityOptions.find(group => group.key === 'intended');
          if (intendedGroup && intendedGroup.children && intendedGroup.children.length > 0) {
            // 80% 概率选择意向高校
            if (Math.random() < 0.8) {
              randomUniversity = intendedGroup.children[Math.floor(Math.random() * intendedGroup.children.length)];
            } else {
              // 20% 概率选择其他高校
              const otherGroup = currentUniversityOptions.find(group => group.key === 'others');
              if (otherGroup && otherGroup.children && otherGroup.children.length > 0) {
                randomUniversity = otherGroup.children[Math.floor(Math.random() * otherGroup.children.length)];
              }
            }
          } else {
            // 如果没有意向高校，从其他高校中选择
            const otherGroup = currentUniversityOptions.find(group => group.key === 'others');
            if (otherGroup && otherGroup.children && otherGroup.children.length > 0) {
              randomUniversity = otherGroup.children[Math.floor(Math.random() * otherGroup.children.length)];
            }
          }
        } else {
          // 如果没有分组，直接从列表中选择
          randomUniversity = currentUniversityOptions[Math.floor(Math.random() * currentUniversityOptions.length)];
        }
      }

      // 设置表单数据
      const newFormData = {
        ...formData.value,
        universityId: randomUniversity ? randomUniversity.value : null,
        courseSeries: randomCourseSeries.value,
        courseName: courseNames[Math.floor(Math.random() * courseNames.length)],
        classDate: Date.now() + Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000, // 未来30天内
        classTime: times[Math.floor(Math.random() * times.length)],
        location: locations[Math.floor(Math.random() * locations.length)],
        plannedHours: [1, 1.5, 2, 2.5, 3, 4][Math.floor(Math.random() * 6)],
        teachingStatus: '计划中',
        teachingSemester: semesterOptions[Math.floor(Math.random() * semesterOptions.length)].value,
        remarks: props.fixedCadre ?
          `为 ${selectedCadre.value?.name || '该干部'} 自动生成的虚拟授课计划数据` :
          '这是自动生成的虚拟授课计划数据',
      };

      // 如果是排课模式，确保干部ID不变
      if (props.fixedCadre && currentCadreId) {
        newFormData.cadreId = currentCadreId;
      }

      formData.value = newFormData;
    }, 100);
  }
};

defineExpose({
  resetForm,
});

onMounted(async () => {
  if (cadreStore.allCadres.length === 0) {
    await cadreStore.fetchCadres();
  }
  if (universityStore.allUniversities.length === 0) {
    await universityStore.fetchUniversities();
  }
});
</script>
